package com.zr.domain.caffeine;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.RemovalListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class CacheListenerConfig {

    @Bean
    public RemovalListener<Object, Object> removalListener() {
        return (key, value, cause) -> {
            String reason = switch (cause) {
                case EXPLICIT -> "手动删除";
                case REPLACED -> "被替换";
                case EXPIRED -> "过期";
                case SIZE -> "超过容量限制";
                default -> "其他原因";
            };
            System.out.printf("缓存条目移除: Key=%s, 原因=%s%n", key, reason);
        };
    }

    // 在Caffeine配置中注册监听器
    @Bean
    public Caffeine<Object, Object> caffeineConfig(RemovalListener<Object, Object> removalListener) {
        return Caffeine.newBuilder()
                .removalListener(removalListener)
                .maximumSize(1000)
                .expireAfterWrite(10, TimeUnit.MINUTES);
    }
}
